package com.example.tnot.api;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 网络工具类，提供通用的JSON构建、POST请求和GET请求方法
 */
public class HttpUtils {
    private static final String TAG = "HttpUtils";

    // 原有buildJsonString方法保持不变
    public static String buildJsonString(HashMap<String, String> params) {
        if (params == null || params.isEmpty()) {
            return "{}";
        }

        try {
            JSONObject jsonObject = new JSONObject();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
            return jsonObject.toString();
        } catch (JSONException e) {
            Log.e(TAG, "构建JSON失败", e);
            return "{}";
        }
    }

    // 原有sendPostRequest方法保持不变
    public static void sendPostRequest(String url, String jsonData, HttpCallback callback) {
        new PostAsyncTask(callback).execute(url, jsonData);
    }

    /**
     * 通用的GET请求发送函数
     * @param url 请求地址
     * @param params 请求参数
     * @param callback 回调接口
     */
    public static void sendGetRequest(String url, HashMap<String, String> params, HttpCallback callback) {
        // 构建带参数的URL
        String fullUrl = buildGetUrl(url, params);
        new GetAsyncTask(callback).execute(fullUrl);
    }

    /**
     * 构建带参数的GET请求URL
     */
    private static String buildGetUrl(String baseUrl, HashMap<String, String> params) {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }

        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        urlBuilder.append("?");

        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                // 对参数进行URL编码，防止特殊字符问题
                String key = URLEncoder.encode(entry.getKey(), "UTF-8");
                String value = URLEncoder.encode(entry.getValue(), "UTF-8");
                urlBuilder.append(key).append("=").append(value).append("&");
            }
            // 移除最后一个多余的&符号
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        } catch (Exception e) {
            Log.e(TAG, "构建GET URL失败", e);
        }

        return urlBuilder.toString();
    }

    /**
     * 回调接口，用于返回请求结果
     */
    public interface HttpCallback {
        void onSuccess(String response) throws JSONException;
        void onFailure(String errorMsg);
    }

    // 原有PostAsyncTask保持不变
    private static class PostAsyncTask extends AsyncTask<String, Void, String> {
        private HttpCallback callback;
        private String errorMsg;

        public PostAsyncTask(HttpCallback callback) {
            this.callback = callback;
        }

        @Override
        protected String doInBackground(String... params) {
            if (params == null || params.length < 2) {
                errorMsg = "请求参数不完整";
                return null;
            }

            String url = params[0];
            String jsonData = params[1];
            HttpURLConnection connection = null;
            OutputStream outputStream = null;
            InputStream inputStream = null;

            try {
                URL requestUrl = new URL(url);
                connection = (HttpURLConnection) requestUrl.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);

                // 发送数据
                outputStream = connection.getOutputStream();
                outputStream.write(jsonData.getBytes("UTF-8"));
                outputStream.flush();

                // 处理响应
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inputStream = connection.getInputStream();
                    return readFromStream(inputStream);
                } else {
                    errorMsg = "服务器响应错误: " + responseCode;
                    return null;
                }
            } catch (Exception e) {
                errorMsg = "请求失败: " + e.getMessage();
                Log.e(TAG, "POST请求异常", e);
                return null;
            } finally {
                // 关闭资源
                try {
                    if (outputStream != null) outputStream.close();
                    if (inputStream != null) inputStream.close();
                    if (connection != null) connection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (callback != null) {
                if (result != null) {
                    try {
                        callback.onSuccess(result);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    callback.onFailure(errorMsg);
                }
            }
        }
    }

    /**
     * 异步任务类，处理GET请求
     */
    private static class GetAsyncTask extends AsyncTask<String, Void, String> {
        private HttpCallback callback;
        private String errorMsg;

        public GetAsyncTask(HttpCallback callback) {
            this.callback = callback;
        }

        @Override
        protected String doInBackground(String... params) {
            if (params == null || params.length == 0) {
                errorMsg = "请求URL不能为空";
                return null;
            }

            String url = params[0];
            HttpURLConnection connection = null;
            InputStream inputStream = null;

            try {
                URL requestUrl = new URL(url);
                connection = (HttpURLConnection) requestUrl.openConnection();
                connection.setRequestMethod("GET"); // 设置为GET请求
                connection.setDoInput(true);
                connection.setDoOutput(false); // GET请求不需要输出流
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);

                // 处理响应
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inputStream = connection.getInputStream();
                    return readFromStream(inputStream);
                } else {
                    errorMsg = "服务器响应错误: " + responseCode;
                    return null;
                }
            } catch (Exception e) {
                errorMsg = "请求失败: " + e.getMessage();
                Log.e(TAG, "GET请求异常", e);
                return null;
            } finally {
                // 关闭资源
                try {
                    if (inputStream != null) inputStream.close();
                    if (connection != null) connection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (callback != null) {
                if (result != null) {
                    try {
                        callback.onSuccess(result);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    callback.onFailure(errorMsg);
                }
            }
        }
    }

    /**
     * 从输入流读取响应数据（共用方法）
     */
    private static String readFromStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }
}